﻿function tryLogin() {
    $("#loginDialog .error").hide();
    $("#loginDialog .loader").fadeIn();

    login($("#loginUsername").val(), $("#loginPassword").val(), function (isSuccessfulLogin) {

        $("#loginDialog .loader").hide();
        if (!isSuccessfulLogin) $("#loginDialog .error").fadeIn(100);
        else {
            $("#loginDialog .error").fadeOut(100);
            $("#loginDialog").slideUp();
            if (bootPos < bootList.length) {
                bootPos++;
                bootUI();
            }
        }
    });
}

function checkLogin(callback) {
    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        dataType: 'json',
        url: 'Services/Auth.svc/CheckLogin'
    })
    .done(function (data, status, xhr) {
        callback(data.d);
    });
}

function requestLogin(callback) {
    showDialog($("#loginDialog"));
}

function ensureLoggedIn(callback) {
    if (readCookie('wamsUI.auth') == null) requestLogin(callback);
    else checkLogin(function (isLoggedIn) {
        if (!isLoggedIn) { eraseCookie("wamsUI.auth"); requestLogin(callback); }
        else if (callback != null) callback();
    });
}
function login(username, password, callback) {

    var postData = {
        username: username,
        password: password
    };
    $.ajax({        
        type: 'POST',
        contentType:'application/json',
        dataType: 'json',
        data: JSON.stringify(postData),
        url: 'Services/Auth.svc/Login'
    })
    .done(function (data, status, xhr) {
        var successLogin = false;
        if (readCookie('wamsUI.auth') != null && data.d == true) successLogin = true;
        callback(successLogin);
    });
}
